<script setup lang="ts">
import useAppStore from '../../../store/modules/app';
import Tools from '../../../utils/tools';
import to from '@/utils/to';
import UserRequest from '@/request/userRequest';
import useToast from '@/hooks/useToast';
import { validatePhone } from '@/utils/validate';

const store = useAppStore();
const { showToast } = useToast();
const show = ref<boolean>(false);
const mobileNumberShow = ref<boolean>(false);
const nikeName = ref<string>(store.$state.userInfo.nickName);
const changePhoneParams = ref<{ phone: string; code: string }>({ phone: '', code: '' });

const time = ref<number>(60);

// 修改用户头像
const handleUpdateUserAvatar = async (e: any) => {
  const { avatarUrl } = e.detail;
  const imgbase64 = await Tools.uniBase64FromFile(avatarUrl);
  await fetchUpdateUserInfo(nikeName.value, imgbase64, '头像');
};

// 修改用户名称
const handleUpdateUserName = async () => {
  await fetchUpdateUserInfo(nikeName.value, store.$state.userInfo.imageUrl, '昵称');
  show.value = false;
};

// input change
const handleInputChange = (e: any) => {
  const { value } = e.detail;
  nikeName.value = value;
};

// 更新用户信息
const fetchUpdateUserInfo = async (nickName: string, image: string, msg: string) => {
  const [err, res] = await to(UserRequest.UpdateUser({ image, nickName }));
  if (err) await showToast(`上传${msg}失败`);
  store.$patch({ userInfo: { ...store.$state.userInfo, nickName, imageUrl: res!.data ? res!.data : store.$state.userInfo.imageUrl } });
  await showToast(`修改${msg}成功`);
};

// 发送验证码
const handleSendVerificationCode = () => {
  if (!validatePhone(changePhoneParams.value.phone)) {
    showToast('手机号格式错误');
    return;
  }
  if (time.value < 60) return;
  UserRequest.FetchSMS({ mobile: changePhoneParams.value.phone, smsType: 103, hasLoading: true }).then(() => {
    showToast('发送验证码成功', 'success');
    time.value -= 1;
    const interval = setInterval(() => {
      time.value -= 1;
      if (time.value === 0) {
        time.value = 60;
        clearInterval(interval);
      }
    }, 1000);
  });
};

// 更换手机号
const handleChangePhoneNumber = (action: string) =>
  new Promise(async (resolve) => {
    if (action === 'confirm') {
      const { phone, code } = changePhoneParams.value;
      if (!validatePhone(changePhoneParams.value.phone)) {
        resolve(false);
        await showToast('手机号格式错误');
      }
      if (!changePhoneParams.value.code) {
        resolve(false);
        await showToast('请输入验证码');
      }
      const [err] = await to(UserRequest.UpdateUserPhone({ phone, code }));
      if (err) {
        resolve(false);
        await showToast('更换号码失败', 'error');
      }
      store.$patch({ userInfo: { ...store.$state.userInfo, phone } });
      mobileNumberShow.value = false;
      changePhoneParams.value = { phone: '', code: '' };
      resolve(true);
      await showToast('更换号码成功');
    } else {
      resolve(true);
    }
  });
</script>

<template>
  <view class="c-pd">
    <view class="mt-[10%] flex flex-col justify-center items-center">
      <van-image width="100px" height="100px" fit="cover" :src="store.$state.userInfo.imageUrl" class="c-br overflow-hidden position-r" />
      <view class="text-[22px] my-[12px]">{{ store.$state.userInfo.nickName }}</view>
      <view class="c-text-color-grey">{{ Tools.ProtectingPhoneNumbers(store.$state.userInfo.phone) }}</view>
    </view>

    <view class="mt-[12px]">
      <van-cell-group inset class="mt-[12px]">
        <van-cell title="修改昵称" is-link @click="show = true">
          <view slot="icon" class="mr-2"> <i class="i-icon-park-outline:edit-name text-[18px]"></i></view>
        </van-cell>
        <van-cell is-link>
          <view slot="icon" class="mr-2"> <i class="i-tabler:photo text-[18px]"></i></view>
          <button class="text-[#333] text-align-left text-[14px] bg-transparent flex items-center h-[100%]" open-type="chooseAvatar" @chooseavatar="handleUpdateUserAvatar">修改头像</button>
        </van-cell>
        <van-cell title="更换绑定手机号" is-link @click="mobileNumberShow = true">
          <view slot="icon" class="mr-2"> <i class="i-lineicons:phone text-[18px]"></i></view>
        </van-cell>
      </van-cell-group>
    </view>

    <van-dialog use-slot title="修改昵称" :show="show" show-cancel-button @cancel="show = false" @confirm="handleUpdateUserName">
      <input class="m-[10px] p-[10px] c-br bg-[#f5f5f5]" type="nickname" v-model="nikeName" placeholder="请输入昵称" @change="handleInputChange" />
    </van-dialog>

    <van-dialog
      use-slot
      title="更换手机号"
      :show="mobileNumberShow"
      show-cancel-button
      @cancel="
        () => {
          mobileNumberShow = false;
          changePhoneParams.code = '';
        }
      "
      :beforeClose="handleChangePhoneNumber"
    >
      <view class="my-[20px]">
        <van-cell-group inset class="w-[100%] mx-0">
          <van-field :placeholder="store.$state.userInfo.phone" type="number" :value="changePhoneParams.phone" @change="changePhoneParams.phone = $event.detail">
            <i slot="left-icon" class="i-fluent:phone-32-regular text-[18px] mr-1"></i>
            <van-button slot="button" :disabled="time < 60" :color="'#ffc300'" size="small" type="primary" @click="handleSendVerificationCode"> {{ time < 60 ? time + 's' : '发送验证码' }} </van-button>
          </van-field>
          <van-field placeholder="请输入验证码" type="number" :value="changePhoneParams.code" @change="changePhoneParams.code = $event.detail">
            <i slot="left-icon" class="i-lets-icons:chat-alt-light text-[18px] mr-1"></i>
          </van-field>
        </van-cell-group>
      </view>
    </van-dialog>
  </view>
</template>
